<template>
  <div class="fulltable">
    <div class="full">
      <div class="add" v-if="isSuperman">  
        <button class="button" @click="dialogVisible = true">➕新增</button>  
      </div> 
      <div class="search">  
  <el-input  
    v-model="nameSearch"  
    placeholder="通过名称搜索"  
    style="width: 200px; margin-right: 10px;" 
    clearable 
  ></el-input>  
  <el-select v-model="adminSearch" placeholder="选择部门负责人" style="width: 200px;" clearable>  
    <el-option  
      v-for="item in deptAdminList"  
      :key="item.id"  
      :label="item.realname"  
      :value="item.realname"  
    ></el-option>  
  </el-select>  
</div>  
    <el-table
    :data="filteredDeptData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"  
    :height="tableHeight"
    border
    style="width: 100%">
    <el-table-column
      prop="deptname"
      label="名称"
      width="130"
      >
    </el-table-column>
    <el-table-column
      prop="address"
      label="地址"
      width="130">
    </el-table-column>
    <el-table-column
      prop="father"
      label="上级部门"
      width="180"
      >
    </el-table-column>
    <el-table-column
      prop="admin"
      label="部门负责人"
      width="180"
      >
    </el-table-column>
     <el-table-column
      prop="tel"
      label="电话"
      width="130">
    </el-table-column>
      <el-table-column
      prop="email"
      label="邮箱"
      width="220">
    </el-table-column>
    <el-table-column
      prop="number"
      label="部门人数"
      width="100"
      >
    </el-table-column>
    <el-table-column
      prop="hc"
      label="部门hc"
      :width="isSuperman ? '100' : ''"
      >
    </el-table-column>
        <el-table-column label="操作" v-if="isSuperman">  
          <template slot-scope="scope">  
            <el-button   
              type="primary"   
              size="small"   
              @click="editItem(scope.row)">编辑</el-button>
            <el-button   
              type="danger"   
              size="small"   
              @click="deleteItem(scope.row)">删除</el-button>  
          </template>  
        </el-table-column>  
  </el-table>
      <div class="paging">
      <el-pagination  
        @size-change="handleSizeChange"  
        @current-change="handleCurrentChange"  
        :current-page="currentPage"  
        :page-sizes="[5,10, 20, 40, 60]"  
        :page-size="pageSize"  
        :pager-count="4"
        layout="total, sizes, prev, pager, next, jumper"  
        :total="filteredDeptData.length">  
      </el-pagination> 
      </div>
  </div>

    <!-- 新增窗口 -->
<el-dialog title="新增部门" :visible.sync="dialogVisible" width="35%">  
  <el-form :model="newDept" :rules="rules" ref="newDeptForm" label-width="80px">  
    <el-form-item label="上级部门" prop="parentDept">  
      <el-cascader  
        v-model="newDept.parentDept"  
        :options="deptOptions"  
        :props="{ checkStrictly: true }"
        placeholder="上级部门">  
      </el-cascader>  
    </el-form-item>  
    <el-form-item label="名称" prop="deptname">  
      <el-input v-model="newDept.deptname"></el-input>  
    </el-form-item>  
    <el-form-item label="地址" prop="address">  
      <el-input v-model="newDept.address"></el-input>  
    </el-form-item>  
    <el-form-item label="电话" prop="tel">  
      <el-input v-model="newDept.tel"></el-input>  
    </el-form-item>  
    <el-form-item label="邮箱" prop="email">  
      <el-input v-model="newDept.email"></el-input>  
    </el-form-item>  
    <el-form-item label="hc数" prop="hc">  
      <el-input v-model="newDept.hc"></el-input>  
    </el-form-item>  
    <el-form-item label="部门负责人" prop="admin" >  
      <el-select v-model="newDept.admin" filterable placeholder="请选择部门负责人">  
        <el-option v-for="item in adminList" :key="item.id" :label="item.realname" :value="item.id"></el-option>  
      </el-select>  
    </el-form-item>  
  </el-form>  
  <div slot="footer" class="dialog-footer">  
    <el-button @click="dialogVisible = false">取 消</el-button>  
    <el-button type="primary" @click="saveNewDept">确 定</el-button>  
  </div>  
</el-dialog>


<!-- 添加编辑弹窗 -->
<el-dialog title="编辑部门" :visible.sync="editDialogVisible" width="35%">  
  <el-form :model="editDept"  ref="editDeptForm" label-width="80px">  
    <el-form-item label="上级部门" prop="parentDept">  
      <div style="display: flex; align-items: center;">
        <el-cascader  
          v-model="editDept.parentDept"  
          :options="deptOptions"  
          :props="{ checkStrictly: true }"
          placeholder="上级部门"
          style="width: 80%;">  
        </el-cascader>  
        <span style="margin-left: 10px; color: #409EFF;">
          当前上级部门: {{ department.father || '无' }}
        </span>
      </div>
    </el-form-item>  
    <el-form-item label="名称" prop="deptname">  
      <el-input v-model="editDept.deptname"></el-input>  
    </el-form-item>  
    <el-form-item label="地址" prop="address">  
      <el-input v-model="editDept.address"></el-input>  
    </el-form-item>  
    <el-form-item label="电话" prop="tel">  
      <el-input v-model="editDept.tel"></el-input>  
    </el-form-item>  
    <el-form-item label="邮箱" prop="email">  
      <el-input v-model="editDept.email"></el-input>  
    </el-form-item>  
    <el-form-item label="hc数" prop="hc">  
      <el-input v-model="editDept.hc" style="width: 180px!important;"></el-input>  
        <span style="margin-left: 26px; color: #409EFF;">
          当前部门人数: {{ department.number || '无' }}
        </span>
    </el-form-item>  
    <el-form-item label="部门负责人" prop="admin">  
      <div style="display: flex; align-items: center;">
        <el-select 
          v-model="editDept.admin" 
          filterable 
          placeholder="请选择部门负责人"
          style="width: 80%;">  
          <el-option 
            v-for="item in adminList" 
            :key="item.id" 
            :label="item.realname" 
            :value="item.id">
          </el-option>  
        </el-select>  
        <span style="color: #409EFF;">
          当前负责人: {{ department.admin || '无' }}
        </span>
      </div>
    </el-form-item>  
  </el-form>  
  <div slot="footer" class="dialog-footer">  
    <el-button @click="editDialogVisible = false">取 消</el-button>  
    <el-button type="primary" @click="saveEditDept">确 定</el-button>  
  </div>  
</el-dialog>
  </div>
</template>

<script>
import {getDeptList,addDept,deleteDeptById,getDeptById,getDeptListTree,updateDept} from '@/api/dept';
import { getUserList,getNotDeptManagerList,getDeptManagerList} from '@/api/user';
import { jwtDecode } from 'jwt-decode'; 
import {addLog} from '@/api/log';
export default {
  data(){
    return {
      dialogVisible: false,  
      detailVisible: false,  // 控制查看详情窗口的显示  
      isSuperman: false,
      logItem:{
              mn:'',
              opn:'',
              res:''
      },
      selectedDept: {
        deptname: '',  
        address: '',  
        tel: '',  
        email: '',  
        admin:null
      },    // 存储被选中的部门信息
      nameSearch: '', // 新增：用于名称搜索  
      adminSearch: null, // 新增：用于部门负责人搜索  
      newDept: {  
        deptname: '',  
        address: '',  
        tel: '',  
        email: '',  
        admin: null,  
        parentDept: [], // 新增字段，用于选择根部门的 ID
        hc:''  
      },  
      cascaderProps: {  
        value: 'nDeptId', // 部门 ID 属性  
        label: 'cDeptName', // 部门名称属性  
        children: 'children' // 子部门属性  
      },  
      deptOptions: [], // 用于存储转换后的部门选项  
      deptAdminList:[],
      rules: {  
        deptname: [  
          { required: true, message: '请输入部门名称', trigger: 'blur' },  
        ],  
        address: [  
          { required: true, message: '请输入部门地址', trigger: 'blur' },  
        ],  
        tel: [  
          { required: true, message: '请输入部门电话', trigger: 'blur' },  
        ],  
        email: [  
          { required: true, message: '请输入部门邮箱', trigger: 'blur' },  
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },  
        ],  
        admin: [  
          { required: true, message: '请选择管理员', trigger: 'change' },  
        ], 
        hc:[{
          required: true,message:'请输入部门hc数',trigger:'blur'
        },] ,
      },  
      adminList:[],
      deptData:[],
        currentPage: 1,  
        pageSize: 5  ,
        tableHeight: 300,  
        maxTableHeight: 700, // 最大高度 600px  
        minTableHeight: 300,
        editDialogVisible: false,
        editDept: {
          id: null,
          deptname: '',
          address: '',
          tel: '',
          email: '',
          admin: null,
          parentDept: [],
          hc: ''
        },
        department: {} // 用于存储当前编辑的部门原始信息
    }
  },
  computed: {  
  filteredDeptData() {  
    return this.deptData.filter(item => {  
      const matchesName = item.deptname.includes(this.nameSearch);  
      const matchesAdmin = this.adminSearch ? item.admin === this.adminSearch : true;  
      return matchesName && matchesAdmin;  
    });  
  },   
},
  created(){
    const token = localStorage.getItem('token'); // 从 localStorage 获取 token  
    if (token) {  
      try {  
        const decoded = jwtDecode(token); // 解码 token  
        this.isSuperman = decoded.role === 'SUPERMAN'; // 判断角色  
      } catch (error) {  
        console.error('Token 解析失败', error);  
      }  
    }  

    this.fetchDeptData(); 
    this.fetchDeptTreeData(); 

    getDeptList().then(response=>{
      this.deptData = response.data
      this.calculateTableHeight() 
      console.log(response.data)
    }).catch(error =>{
      console.log(error)
      this.tableHeight = this.minTableHeight 
    }),
    this.getAdminList();
    this.getDeptAdmins();
  },
    watch:{
      "nameSearch"(newVal){
        if(this.nameSearch!=""){
        this.logItem.mn = "nameSearch";
        this.logItem.opn = "通过名称搜索部门";
        this.logItem.res = "true";
        addLog(this.logItem);
        }else{
          this.logItem.mn = "nameSearch";
          this.logItem.opn = "清空名称搜索部门";
          this.logItem.res = "true";
          addLog(this.logItem);
        }
      },
      "adminSearch"(newVal){
        if(this.adminSearch!=""){
        this.logItem.mn = "adminSearch";
        this.logItem.opn = "通过部门负责人搜索部门";
        this.logItem.res = "true";
        addLog(this.logItem);
        }else{
          this.logItem.mn = "adminSearch";
          this.logItem.opn = "清空部门负责人搜索部门";
          this.logItem.res = "true";
          addLog(this.logItem);
        }
      },
  currentPage() {  
    this.calculateTableHeight()  
  },  
  pageSize() {  
    this.calculateTableHeight()  
  }
  },
  methods:{
      fetchDeptTreeData() {  
      getDeptListTree().then(response => {  
        this.deptOptions = this.convertDeptData(response.data); // 将返回的数据转换为 cascader 所需的格式  
      }).catch(error => {  
        console.error(error);  
        // 处理错误  
      });  
    }, 
    getDeptAdmins(){
      getDeptManagerList().then(response=>{
        this.deptAdminList = response.data;
      }).catch(error=>{
        console.error(error)
      })
    },
    handleSizeChange(val) {  
      this.pageSize = val;  
      this.currentPage = 1;  
      this.logItem.mn = "handleSizeChange";
      this.logItem.opn = "改变每页显示的部门数量";
      this.logItem.res = "true";
      addLog(this.logItem);
    },  
    handleCurrentChange(val) {  
      this.currentPage = val;  
      this.logItem.mn = "handleCurrentChange";
      this.logItem.opn = "改变页码-部门管理";
      this.logItem.res = "true";
      addLog(this.logItem);
    },
  calculateTableHeight() {  
    // 获取当前页展示的数据量  
    const currentPageData = this.deptData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);  
    
    // 每行高度为 50px，再加上表头高度 50px，得到总高度  
    let height = (currentPageData.length + 1) * 60
    // 限制高度在 minTableHeight 和 maxTableHeight 之间  
    this.tableHeight = Math.max(this.minTableHeight, Math.min(height, this.maxTableHeight))  
  },fetchDeptData() {  
  getDeptList().then(response => {  
    this.deptData = response.data; // 更新部门数据  
    this.calculateTableHeight();  
  }).catch(error => {  
    console.error(error);  
    this.tableHeight = this.minTableHeight;  
  });  
} ,
    convertDeptData(deptData) {  
      return deptData.map(dept => ({  
        value: dept.id, // 假设你的部门ID属性为 id  
        label: dept.deptname, // 假设你的部门名称属性为 deptname  
        children: dept.children ? this.convertDeptData(dept.children) : [] // 处理子部门  
      }));  
    },  
    saveNewDept() {  
      // 保存新增部门的逻辑  
      this.$refs.newDeptForm.validate((valid) => {  
        if (valid) {  
          console.log('保存新增部门:', this.newDept);  
          addDept(this.newDept).then((response) => {  
            this.logItem.mn = "saveNewDept";
            this.logItem.opn = "新增部门";
            this.logItem.res = "true";
            addLog(this.logItem);
            this.$message.success('新部门添加成功');  
            this.dialogVisible = false;  
            this.newDept = { // 重新设置 newDept  
              deptname: '',  
              address: '',  
              tel: '',  
              email: '',  
              admin: null,  
              parentDept: [],
              hc:''  
            };  
            this.selectedDept = null;  // 清空选定的部门  
            window.location.reload();  
          });  
        } else {  
          // 表单验证失败  
          this.$message.error('新部门添加失败');  
          this.logItem.mn = "saveNewDept";
          this.logItem.opn = "新增部门";
          this.logItem.res = "false";
          addLog(this.logItem);
          return false;  
        }  
      });  
    }, 
    //获取为正式员工且不为部门负责人的list
     getAdminList() {  
      getNotDeptManagerList().then((response) => {  
        console.log(response.data)
        this.adminList = response.data;  
      });  
    },
    deleteItem(department) {  
    this.$confirm(`确定删除部门 ${department.deptname} 吗?`, '警告', {  
      confirmButtonText: '确定',  
      cancelButtonText: '取消',  
      type: 'warning'  
    }).then(() => {  
      // 调用删除 API  
      deleteDeptById(department.id).then(() => {  
        // 从 deptData 数组中移除部门  
        this.deptData = this.deptData.filter(item => item.id !== department.id);  
        this.$message.success('删除成功');  
        this.logItem.mn = "deleteItem";
          this.logItem.opn = "删除部门";
          this.logItem.res = "true";
          addLog(this.logItem);
        window.location.reload()  
      }).catch(error => {  
        console.error(error);  
        this.logItem.mn = "deleteItem";
          this.logItem.opn = "删除部门";
          this.logItem.res = "false";
          addLog(this.logItem);
        this.$message.error('删除失败');  
      });  
    }).catch(() => {  
      this.$message.info('已取消删除');  
    });  
  },
    viewItem(department) {  
      getDeptById(department.id).then((response)=>{
        console.log(response.data)
        this.selectedDept = response.data;
        this.detailVisible = true;  
      })
  },     
    editItem(department) {
      // 保存当前部门的原始信息
      this.department = { ...department };
      
      this.editDept = {
        id: department.id,
        deptname: department.deptname,
        address: department.address,
        tel: department.tel,
        email: department.email,
        admin: department.adminId,
        parentDept: department.parentId ? [department.parentId] : [],
        hc: department.hc
      };
      this.editDialogVisible = true;
    },
    saveEditDept() {
      this.$refs.editDeptForm.validate((valid) => {
        if (valid) {
          // console.log("更新的部门信息",this.editDept);
          updateDept(this.editDept).then(response => {
            this.$message.success('部门信息更新成功');
            this.editDialogVisible = false;
            this.logItem.mn = "saveEditDept";
            this.logItem.opn = "编辑部门信息";
            this.logItem.res = "true";
            addLog(this.logItem);
            // 刷新页面或更新列表
            window.location.reload();
          }).catch(error => {
            console.error('更新失败:', error);
            this.logItem.mn = "saveEditDept";
            this.logItem.opn = "编辑部门信息";
            this.logItem.res = "false";
            addLog(this.logItem);
            this.$message.error('部门信息更新失败');
          });
        } else {
          return false;
        }
      });
    }
  } 
}
</script>

<style lang="less" scoped>
.fulltable{
  margin-top: 20px;
  height: 700px;
}
.full{
  height: 800px;
  margin: 0;
  padding: 0;
  background: pink;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;
}
.add{
  padding: 10px;
}
/deep/.el-table .cell {  
  color: black;
}  
.button{
  background: #788fd3;
  color: white;
}

.paging{
  margin: 0;
  padding: 0;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;

  /deep/ .el-pagination {
    display: flex;  
    justify-content: flex-end;  
  }
}
/deep/ .el-form {
  .el-form-item__label{
    width: 20% !important;
  }
  .el-input{
    width: 80% !important;
  }
}

.current-value {
  margin-left: 10px;
  color: #409EFF;
  font-size: 14px;
}

/deep/ .el-form {
  .el-form-item__content {
    display: flex;
    align-items: center;
  }
  
  .el-cascader, .el-select {
    flex: 1;
  }
}
</style>